from rest_framework import serializers
from ..models.prefixModel import *
from ..config.message_config import Search_message, Search_message_type


class PrefixListQuerySerializer(serializers.Serializer):
    prefix_name = serializers.CharField(required=False, allow_blank=True)
    sei_id = serializers.CharField(required=False, allow_blank=True)
    prefix_symbol = serializers.CharField(required=False, allow_blank=True)
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False, allow_blank=True)
    sort_order = serializers.CharField(required=False, allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "prefix_name" in attrs:
            attrs["prefix_name"] = attrs["prefix_name"].strip()
            if attrs["prefix_name"] == "":
                attrs.pop("prefix_name")
        if "sei_id" in attrs:
            attrs["sei_id"] = attrs["sei_id"].strip()
            if attrs["sei_id"] == "":
                attrs.pop("sei_id")
        if "prefix_symbol" in attrs:
            attrs["prefix_symbol"] = attrs["prefix_symbol"].strip()
            if attrs["prefix_symbol"] == "":
                attrs.pop("prefix_symbol")
        if ("prefix_name" not in attrs or attrs["prefix_name"] == "") and ("sei_id" not in attrs or attrs["sei_id"] == "") and ("prefix_symbol" not in attrs or attrs["prefix_symbol"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': "{} : {}".format(Search_message_type.get("SEARCH_FAIL"), Search_message.get("SEARCH_BROAD"))
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': "{} : {},{}".format(Search_message_type.get("SEARCH_FAIL"), Search_message.get("SEARCH_PARAM_ERROR"), str(e.detail))
            })
        return attrs

    @classmethod
    def get_query_fields(self):
        return [{"title": "单位词头名称：", "dataIndex": "prefix_name", "type": "CharField"},
                {"title": "单位词头编码：", "dataIndex": "sei_id", "type": "CharField"},
                {"title": "单位词头符号：", "dataIndex": "prefix_symbol", "type": "CharField"}]


class PrefixListSerializer(serializers.ModelSerializer):
    prefix_name = serializers.SerializerMethodField()
    prefix_other_symbol = serializers.SerializerMethodField()

    class Meta:
        model = UnitPrefix
        fields = ["uuid", "prefix_name", "sei_id", "prefix_base", "prefix_power",
                  "prefix_symbol", "prefix_other_symbol", "prefix_description", "prefix_comment"]

    def get_prefix_name(self, obj):
        if obj.prefix_name != "" and obj.prefix_name_en != "":
            return "{}({})".format(obj.prefix_name, obj.prefix_name_en)
        elif obj.prefix_name != "":
            return obj.prefix_name
        elif obj.prefix_name_en != "":
            return obj.prefix_name_en
        else:
            return "error"
        
        
    
    def get_prefix_other_symbol(self, obj):
        symbol_dict = {}
        symbol_ascii = obj.get('prefix_symbol_ascii') if isinstance(
            obj, dict) else obj.prefix_symbol_ascii
        if symbol_ascii != "" and symbol_ascii != None:
            symbol_dict["单位词头ascii符号"] = symbol_ascii
        symbol_html = obj.get('prefix_symbol_html') if isinstance(
            obj, dict) else obj.prefix_symbol_html
        if symbol_html != "" and symbol_html != None:
            symbol_dict["单位词头html符号"] = symbol_html
        symbol_latex = obj.get('prefix_symbol_latex') if isinstance(
            obj, dict) else obj.prefix_symbol_latex
        if symbol_latex != "" and symbol_latex != None:
            symbol_dict["单位词头latex符号"] = symbol_latex
        symbol_unicode = obj.get('prefix_symbol_unicode') if isinstance(
            obj, dict) else obj.prefix_symbol_unicode
        if symbol_unicode != "" and symbol_unicode != None:
            symbol_dict["单位词头unicode符号"] = symbol_unicode
        symbol_dict_str = '\n'.join(
            f'{key}: {value}' for key, value in symbol_dict.items())
        return symbol_dict_str

    @classmethod
    def get_extra_fields_info(self):
        return [
            {"title": "单位词头名称", "dataIndex": "prefix_name", "type": "CharField"},
            {"title": "单位词头其他符号信息", "dataIndex": "prefix_other_symbol", "type": "TextField"},]


class PrefixCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = UnitPrefix
        fields = ["prefix_name", "prefix_name_en","sei_id", "prefix_base", "prefix_power",
                  "prefix_symbol", "prefix_symbol_ascii", "prefix_symbol_html", "prefix_symbol_latex", "prefix_symbol_unicode",
                  "prefix_description","prefix_description_en", "prefix_comment"]
    def to_internal_value(self, data):
        # 调用父类方法以确保基本验证正常运行
        data = super().to_internal_value(data)

        # 遍历所有字段，对字符串类型数据进行 strip
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data
        
class PrefixModifyOutputSerializer(serializers.ModelSerializer):
    class Meta:
        model = UnitPrefix
        fields = ["uuid", "prefix_name", "prefix_name_en","sei_id", "prefix_base", "prefix_power",
                  "prefix_symbol", "prefix_symbol_ascii", "prefix_symbol_html", "prefix_symbol_latex", "prefix_symbol_unicode",
                  "prefix_description","prefix_description_en", "prefix_comment"]
    
    
class PrefixInfoSerializer(serializers.ModelSerializer):
    create_person = serializers.SerializerMethodField()
    modify_person = serializers.SerializerMethodField()
    class Meta:
        model = UnitPrefix
        fields = ["prefix_name", "prefix_name_en","sei_id", "prefix_base", "prefix_power",
                  "prefix_symbol", "prefix_symbol_ascii", "prefix_symbol_html", "prefix_symbol_latex", "prefix_symbol_unicode",
                  "prefix_description","prefix_description_en", "prefix_comment","create_person","create_date","modify_person","modify_date"]
    def get_create_person(self,obj):
        return obj.create_person.user_name
    def get_modify_person(self,obj):
        return obj.modify_person.user_name
        
class PrefixModifyInfoInputSerializer(serializers.ModelSerializer):
    class Meta:
        model = UnitPrefix
        fields = ["prefix_name", "prefix_name_en","sei_id", "prefix_base", "prefix_power",
                  "prefix_symbol", "prefix_symbol_ascii", "prefix_symbol_html", "prefix_symbol_latex", "prefix_symbol_unicode",
                  "prefix_description","prefix_description_en", "prefix_comment"]
    
    def to_internal_value(self, data):
        # 调用父类方法以确保基本验证正常运行
        data = super().to_internal_value(data)

        # 遍历所有字段，对字符串类型数据进行 strip
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data
    
    # def validate_prefix_name(self,value):
    #     instance = self.instance
    #     if instance and instance.prefix_name == value:
    #         return value
    #     return value
        
    # def validate_prefix_name_en(self,value):
    #     instance = self.instance
    #     if instance and instance.prefix_name_en == value:
    #         return value
    #     return value
    
    # def validate_sei_id(self,value):
    #     instance = self.instance
    #     if instance and instance.sei_id == value:
    #         return value
    #     return value
